package Server;

import Data.GroupData;
import Data.MassageData;
import Search.SearchFriendFromGroup;
import Search.SearchMassage;
import Search.SearchMassageFromGroup;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.sql.*;

public class SetGroup {
    private GroupData groupData=new GroupData();

    String url = "jdbc:mysql://127.0.0.1:3306/nox?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8";
    String user = "root";
    String password = "Mi20030610.";

    public GroupData setgroup(String group_id) throws ClassNotFoundException, SQLException, IOException {
        //查找群聊简介
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection Conn = DriverManager.getConnection(url, user, password);

        String search_group_sql="select *from chat_room_list where group_id=?;";
        PreparedStatement operation=Conn.prepareStatement(search_group_sql);
        operation.setString(1,group_id);

        ResultSet resultSet=operation.executeQuery();
        if(resultSet.next())
        {
            groupData.setGroup_id(group_id);
            groupData.setGroup_name(resultSet.getString("name"));
            groupData.setCreater_id(resultSet.getString("creater_id"));
            groupData.setGroup_saying(resultSet.getString("group_saying"));

            String avatar_path=resultSet.getString("group_avatar");
            if(avatar_path!=null)
            {
                File file=new File(avatar_path);
                byte[] t;
                if (file.exists())
                {
                    byte[] buffer = new byte[1024*5];
                    t = new byte[(int) file.length()];
                    InputStream is = Files.newInputStream(file.toPath());
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    int len;
                    while ((len = is.read(buffer)) != -1)
                    {
                        bos.write(buffer, 0, len);
                    }
                    t = bos.toByteArray();
                    groupData.setGroup_avatar(t);
                }
                else groupData.setGroup_avatar(null);
            }
            else groupData.setGroup_avatar(null);

            //已经读取完群聊简介的消息
            operation.close();
            //设置群聊的聊天记录
//            MassageData massageData=new MassageData();
//            massageData.setReceiver(group_id);
//            massageData.setSum(0);
//
//            SearchMassageFromGroup searchMassageFromGroup=new SearchMassageFromGroup(massageData);
//            groupData.setMassageListData(searchMassageFromGroup.searchMassage());

            //设置群聊的好友列表
//            SearchFriendFromGroup searchFriend=new SearchFriendFromGroup(group_id);
//            groupData.setGroup_friend_list(searchFriend.getFriendListFromGroup());
        }
        return groupData;
    }
}
